<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
             label-width="68px">
      <el-form-item label="所属栏目" prop="categoryId">
        <el-cascader
          v-model="queryParams.categoryId"
          placeholder="请选择所属栏目"
          :options="categoryOptions"
          :props="{
                        value: 'id',
                        label: 'categoryTitle',
                        children: 'children',
                        checkStrictly: true,
                        emitPath: true, // 确保返回完整路径
                        expandTrigger: 'click',
                        checkStrictly: true
                    }"
          clearable
          @change="handleCategoryChange"
          @visible-change="handleVisibleChange"
          popper-class="category-cascader"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="是否是叶子节点" prop="leaf">
        <el-select v-model="queryParams.leaf" placeholder="请选择是否是叶子节点" clearable>
          <el-option label="是叶子节点" value="1"></el-option>
          <el-option label="非叶子节点" value="0"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="名称" prop="categoryTitle">
        <el-input v-model="queryParams.categoryTitle" placeholder="请输入栏目名称" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>


      <el-form-item label="显示状态" prop="categoryDisplay">
        <el-select v-model="queryParams.categoryDisplay" placeholder="请选择栏目是否显示" clearable>
          <el-option label="enable" value="enable"></el-option>
          <el-option label="disable" value="disable"></el-option>
        </el-select>
      </el-form-item>


      <el-form-item label="删除状态" prop="del">
        <el-select v-model="queryParams.del" placeholder="请选择删除标记" clearable>
          <el-option label="已删除" value="1"></el-option>
          <el-option label="未删除" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['cms:category:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['cms:category:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                   @click="handleDeleteBatch" v-hasPermi="['cms:category:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="categoryList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!-- <el-table-column label="类别ID" align="center" prop="id" /> -->
      <el-table-column label="父级分类" align="center" width="180">
        <template slot-scope="scope">
          <span>{{ getParentCategoryName(scope.row.categoryId) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="栏目名称" align="center">
        <template slot-scope="scope">
          <el-tooltip
            placement="top"
            :content="scope.row.categoryDescrip || '暂无描述'"
            effect="dark"
          >
            <div style="cursor: pointer;">{{ scope.row.categoryTitle }}</div>
          </el-tooltip>
          <!-- <div>{{ scope.row.categoryDescrip }}</div> -->
          <!-- <div>拼音：{{ scope.row.categoryPinyin }}</div> -->
        </template>
      </el-table-column>

      <el-table-column label="是否是叶子节点" align="center" prop="leaf">
        <template slot-scope="scope">
          <span>{{ scope.row.leaf === '1' || scope.row.leaf === 1 ? '叶子节点' : '非叶子节点' }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column label="栏目banner图" align="center" prop="categoryImg" /> -->
      <!-- <el-table-column label="栏目属性" align="center" prop="categoryFlag" /> -->
      <el-table-column label="栏目属性" align="center" prop="categoryType"/>
      <el-table-column label="自定义顺序" align="center" prop="categorySort"/>
      <el-table-column label="创建/修改时间" align="center">
        <template slot-scope="scope">
          <div>创建：{{ parseTime(scope.row.createDate) }}</div>
          <div>修改：{{ parseTime(scope.row.updateDate) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="显示状态" align="center" prop="categoryDisplay">
        <template slot-scope="scope">
          <span>{{
              scope.row.categoryDisplay === 'enable' ? '展示' : scope.row.categoryDisplay === 'disable' ? '不展示' : scope.row.categoryDisplay
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="删除标记" align="center" prop="del">
        <template slot-scope="scope">
          <span>{{ scope.row.del === '1' || scope.row.del === 1 ? '已删除' : '未删除' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-if="scope.row.del !==1 "
                     v-hasPermi="['cms:category:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-if="scope.row.del !==1 "
                     v-hasPermi="['cms:category:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 添加或修改分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属栏目" prop="categoryId">
          <el-cascader
            v-model="form.categoryId"
            placeholder="请选择所属栏目"
            :options="categoryOptions"
            :props="{ value: 'id', label: 'categoryTitle', children: 'children', checkStrictly: true }"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="是否是叶子节点" prop="leaf">
          <el-select v-model="form.leaf" placeholder="请选择是否是叶子节点">
            <el-option label="是叶子节点" value="1"></el-option>
            <el-option label="非叶子节点" value="0"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="栏目名称" prop="categoryTitle">
          <el-input v-model="form.categoryTitle" placeholder="请输入栏目名称"/>
        </el-form-item>
        <!-- <el-form-item label="栏目banner图" prop="categoryImg">
            <el-input v-model="form.categoryImg" type="textarea" placeholder="请输入内容" />
        </el-form-item> -->
        <!-- <el-form-item label="栏目小图" prop="categoryIco">
            <el-input v-model="form.categoryIco" type="textarea" placeholder="请输入内容" />
        </el-form-item> -->
        <el-form-item label="栏目副标题" prop="categoryShortTitle">
          <el-input v-model="form.categoryShortTitle" placeholder="请输入栏目副标题"/>
        </el-form-item>
        <!-- <el-form-item label="栏目属性" prop="categoryFlag">
            <el-input v-model="form.categoryFlag" placeholder="请输入栏目属性" />
        </el-form-item> -->
        <el-form-item label="栏目是否显示" prop="categoryDisplay">
          <el-select v-model="form.categoryDisplay" placeholder="请选择栏目是否显示">
            <el-option label="显示" value="enable"></el-option>
            <el-option label="不显示" value="disable"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="栏目描述" prop="categoryDescrip">
          <el-input v-model="form.categoryDescrip" type="textarea" placeholder="请输入内容"/>
        </el-form-item>

        <el-form-item label="栏目路径" prop="categoryPath">
          <el-input v-model="form.categoryPath" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="自定义链接" prop="categoryDiyUrl">
          <el-input v-model="form.categoryDiyUrl" placeholder="请输入自定义链接"/>
        </el-form-item>
        <el-form-item label="栏目拼音" prop="categoryPinyin">
          <el-input v-model="form.categoryPinyin" placeholder="请输入栏目拼音"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addCategory,
  batchDelCategory,
  delCategory,
  getCategory,
  listAllCategory,
  listTreeCategory,
  updateCategory
} from "@/api/cms/category";

export default {
  name: "Category",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分类表格数据
      categoryList: [],
      // 分类树形选项
      categoryOptions: [],
      // 分类ID到名称的映射
      categoryMap: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        leaf: null,
        dictId: null,
        categoryTitle: null,
        categoryShortTitle: null,
        categoryFlag: null,
        categoryDisplay: null,
        categoryKeyword: null,
        categoryType: null,
        categoryPinyin: null,
        createDate: null,
        del: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        leaf: [
          { required: true, message: '请选择是否是叶子节点', trigger: 'change' }
        ],
        categoryTitle: [
          { required: true, message: '请输入栏目名称', trigger: 'blur' }
        ],
        categoryDisplay: [
          { required: true, message: '请选择栏目是否显示', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getCategoryTree()
    this.getAllCategory()
  },
  methods: {
    /** 查询分类列表 */
    getList() {
      this.loading = true
      // 处理查询参数中的级联选择器值
      const queryParams = {...this.queryParams}
      // 如果categoryId是数组，只取最后一级ID
      if (Array.isArray(queryParams.categoryId) && queryParams.categoryId.length > 0) {
        queryParams.categoryId = queryParams.categoryId[queryParams.categoryId.length - 1]
      }

      // 使用树形结构API获取数据
      listTreeCategory(queryParams).then(response => {
        try {
          // 处理树形数据，确保格式正确
          let treeData = response && response.data ? response.data : []
          this.categoryList = treeData
          this.loading = false
        } catch (err) {
          console.error('处理树形数据失败:', err)
          this.categoryList = []
          this.loading = false
        }
      }).catch(error => {
        console.error('获取分类树失败:', error)
        this.categoryList = []
        this.loading = false
      })
    },

    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },

    /** 根据ID获取父级分类名称 - 使用Map快速查找 */
    getParentCategoryName(id) {
      if (!id || id === 0) {
        return '顶级分类';
      }

      // 从categoryMap中直接查找
      return this.categoryMap[id] || '未知分类';
    },

    /** 获取分类树形结构 */
    getCategoryTree() {
      // 首先设置默认的mock数据，确保页面能正常显示
      this.categoryOptions = []

      // 尝试从API获取数据
      try {
        listTreeCategory().then(response => {
          try {
            // 处理树形数据，确保格式正确
            const data = response && response.data ? response.data : []
            this.categoryOptions = data
          } catch (err) {
            console.error('处理树形数据失败:', err)
          }
        }).catch(error => {
          console.error('获取分类树失败:', error)
          // 保持使用mock数据
        })
      } catch (error) {
        console.error('调用API失败:', error)
        // 保持使用mock数据
      }
    },

    /** 获取所有分类列表并构建ID到名称的映射 */
    getAllCategory() {
      listAllCategory({}).then(response => {
        const data = response.data || []
        debugger
        // 构建ID到名称的映射
        this.categoryMap = {}
        if (Array.isArray(data)) {
          data.forEach(item => {
            // 确保有必要的属性
            if (item.id && item.categoryTitle) {
              this.categoryMap[item.id] = item.categoryTitle
            }
          })
        }

        console.log('分类ID到名称的映射:', this.categoryMap)
        debugger
      }).catch(error => {
        console.error('获取所有分类列表失败:', error)
        // 出错时使用空映射
        this.categoryMap = {}
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        categoryId: [], // 使用数组存储级联选择器的值
        leaf: null,
        topId: null,
        dictId: null,
        mdiyModelId: null,
        mdiyCategoryModelId: null,
        categoryParentIds: null,
        categoryTitle: null,
        categoryImg: null,
        categoryIco: null,
        categoryShortTitle: null,
        categoryFlag: null,
        categoryDisplay: null,
        categoryIsSearch: null,
        categoryDescrip: null,
        categoryKeyword: null,
        categoryPath: null,
        categoryDiyUrl: null,
        categoryUrl: null,
        categoryListUrl: null,
        categoryType: null,
        categoryPinyin: null,
        categorySort: null,
        isChild: null,
        updateDate: null,
        updateBy: null,
        createDate: null,
        createBy: null,
        del: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 栏目选择变化时自动查询 */
    handleCategoryChange() {
      this.handleQuery()
    },

    /** 处理级联选择器显示/隐藏时的逻辑 */
    handleVisibleChange(visible) {
      // 确保组件正常显示和交互
      if (!visible && this.queryParams.categoryId) {
        // 当选择器关闭且有值时，确保查询正确执行
        this.handleQuery()
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      // 重置查询参数中的categoryId为null
      this.queryParams.categoryId = null
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加分类"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getCategory(id).then(response => {
        this.form = response.data
        // 将单个ID转换为级联选择器需要的数组格式
        if (this.form.categoryId) {
          // 这里简化处理，实际应用中可能需要构建完整的路径数组
          this.form.categoryId = [this.form.categoryId]
        } else {
          this.form.categoryId = []
        }
        // 确保leaf字段值正确显示在下拉选项中
        if (this.form.leaf !== undefined && this.form.leaf !== null) {
          this.form.leaf = String(this.form.leaf);
        }
        this.open = true
        this.title = "修改分类"
      })
    },
    /** 提交按钮 */
    submitForm() {
      if (!this.$refs["form"]) {
        console.error('表单引用不存在')
        return
      }

      this.$refs["form"].validate(valid => {
        if (valid) {
          try {
            // 处理级联选择器的值，只取最后一级ID
            const submitForm = {...this.form}
            if (Array.isArray(submitForm.categoryId) && submitForm.categoryId.length > 0) {
              submitForm.categoryId = submitForm.categoryId[submitForm.categoryId.length - 1]
            } else {
              submitForm.categoryId = null
            }

            const isUpdate = submitForm.id != undefined;
            const request = isUpdate ? updateCategory(submitForm) : addCategory(submitForm);

            request.then(response => {
              const message = isUpdate ? "修改成功" : "新增成功";
              this.$modal.msgSuccess(message);
            }).catch(error => {
              console.error(isUpdate ? '修改失败:' : '新增失败:', error);
              this.$modal.msgError(isUpdate ? "修改失败" : "新增失败");
            }).finally(() => {
              // Ensure refresh happens regardless of success or failure
              this.refreshAllData();
              this.open = false;
            });
          } catch (error) {
            console.error('提交表单时出错:', error);
            this.$modal.msgError("操作异常");
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      try {
        this.$modal.confirm('是否确认删除名称为"' + (row.categoryTitle || '未命名') + '"的数据项？')
          .then(() => delCategory(row.id))
          .then(() => {
            this.$modal.msgSuccess("删除成功");
          })
          .catch(error => {
            if (error !== 'cancel') {  // Don't show error when user cancels
              console.error('删除失败:', error);
              this.$modal.msgError("删除失败");
            }
          })
          .finally(() => {
            // Always refresh data after attempting deletion
            this.refreshAllData();
          });
      } catch (error) {
        console.error('删除操作出错:', error);
      }
    },

    handleDeleteBatch() {
      // 批量删除
      const ids = this.ids;
      this.$modal.confirm('是否确认删除选中的数据项？')
        .then(() => batchDelCategory(ids))
        .then(() => {
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
          this.$modal.msgError("删除失败");
        })
        .finally(() => {
          // Always refresh data after attempting deletion
          this.refreshAllData();
        });
    },

// Add a comprehensive refresh method
    refreshAllData() {
      this.getList();
      this.getCategoryTree();
      this.getAllCategory();
    }

  }
}
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

/* 确保级联选择器中点击标签也能选中选项 */
:deep(.el-cascader-menu__item) {
  cursor: pointer;
}

:deep(.el-cascader-menu__item-content) {
  cursor: pointer;
}

:deep(.el-cascader-menu__item:hover) {
  background-color: #f5f7fa;
}
</style>
